//
//  ShouYeAddressController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/7/28.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "ShouYeAddressController.h"
#import "MyAddressCell.h"

#import "AddAddressInfoController.h"//添加地址
#import "TextFiledAddImage.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "ZYLPickerView.h"

#import <AMapFoundationKit/AMapFoundationKit.h>

#import <AMapSearchKit/AMapSearchKit.h>

#import "SeachAddressView.h"//搜索view

#import "KongView.h"
#import "AddressListModel.h"
#import "AddressBackView.h"
#import<CommonCrypto/CommonDigest.h>


@interface ShouYeAddressController ()<UITableViewDelegate, UITableViewDataSource,searchChooseAddressDelgate>
{
    UITextField *seachField;//搜索框
    NSString *proviceStr;
}
@property (nonatomic, strong)    AMapLocationManager *locationManager;


@property (nonatomic, strong)NSMutableArray *dataArray;
//无地址时加载图
@property (nonatomic, strong)UIImageView *imageV;
@property (nonatomic, strong)UILabel *twoLabel;
@property (nonatomic, strong)UIButton *daiNiFeiBtn;

@property (assign, nonatomic) BOOL isBool;

@property (nonatomic, strong)AMapSearchAPI *search;

@property (nonatomic, strong)NSMutableArray *addressArray;
@property (nonatomic, strong)SeachAddressView *seachView;//搜索tableView

@property (nonatomic, strong)KongView *kongview;//搜索地址为空要显示的视图
@property (nonatomic, strong)AddressBackView *addressBackView;


@end

@implementation ShouYeAddressController
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    _addressArray = [NSMutableArray array];
    [self getData];

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
   
     self.isBool = YES;
    _dataArray = [NSMutableArray array];
    _addressBt.titleLabel.lineBreakMode =  NSLineBreakByTruncatingTail;
    [self configureView];
    //[self getData];
    
   
  
    
   
}

- (NSString *) md5:(NSString *) input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        
        [output appendFormat:@"%02x", digest[i]];
    return  output;
    
}

//获取数据
- (void)getData {
   [MBProgressHUD showMessage:@"正在获取地址列表"];
    //取本地的userid
    NSDictionary *saveDic = [SaveDataMethord readLoginData];

    NSDictionary *dic = @{@"userid":saveDic[@"userid"],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};

    [HttpRequest getWithURLString:POST(GetAllAddress) parameters:dic success:^(id responseObject) {
        [MBProgressHUD hideHUD];
       
        if ([responseObject[@"ret"] intValue] != 200) {
            [MBProgressHUD showText:@"网络错误"];
            return ;
        }
        
        NSArray *tempA = responseObject[@"data"][@"info"];
        for (NSDictionary *tempD in tempA) {
            AddressListModel *model = [[AddressListModel alloc] init];
            [model setValuesForKeysWithDictionary:tempD];
            [self.addressArray addObject:model];
           
        }
        
         [self.tableView reloadData];
    
        if (self.addressArray.count == 0) {
            self.tableView.hidden = YES;
            if (_imageV) {
                [_imageV removeFromSuperview];
            }
            
            if (_twoLabel) {
                [_twoLabel removeFromSuperview];
            }
            if (_daiNiFeiBtn) {
                [_daiNiFeiBtn removeFromSuperview];
            }
            
            _imageV = [[UIImageView alloc] init];
            _imageV.frame = CGRectMake(kScreen_Width/2-75, 230, 150, 150);
            _imageV.image = [UIImage imageNamed:@"zanwudizhi"];
            [self.view addSubview:_imageV];
            [self.tableView.mj_footer endRefreshing];
            _twoLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreen_Width/2-100, CGRectGetMaxY(_imageV.frame)+20, 200, 30)];
            _twoLabel.text = @"暂无地址，快来添加地址吧";
            _twoLabel.textColor = [UIColor grayColor];
            _twoLabel.font = kFont14;
            _twoLabel.textAlignment = NSTextAlignmentCenter;
            [self.view addSubview:_twoLabel];
            
            _daiNiFeiBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
            _daiNiFeiBtn.frame = CGRectMake(50, CGRectGetMaxY(_twoLabel.frame)+20, kScreen_Width - 100, 45);
            [_daiNiFeiBtn setBackgroundImage:[UIImage imageNamed:@"bg1"] forState:(UIControlStateNormal)];
            [_daiNiFeiBtn setTitle:@"添加地址" forState:(UIControlStateNormal)];
            _daiNiFeiBtn.layer.masksToBounds = YES;
            _daiNiFeiBtn.layer.cornerRadius = 3;
            [_daiNiFeiBtn addTarget:self action:@selector(addAddressBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
            [self.view addSubview:_daiNiFeiBtn];
        }
        else {
            self.tableView.hidden = NO;
            [_daiNiFeiBtn removeFromSuperview];
            [_twoLabel removeFromSuperview];
            [_imageV removeFromSuperview];
        }

    } failure:^(NSError *error) {
        
    }];
    
   
 
}
- (void)configureView {

    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg1"]];
    imgView.frame = self.bgcView.bounds;
    imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.bgcView insertSubview:imgView atIndex:0];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = kSpNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"MyAddressCell" bundle:nil] forCellReuseIdentifier:@"MyAddressCell"];
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 返回按钮的点击事件
- (IBAction)backBtn:(UIButton *)sender {
 
    
   if (self.addressArray.count == 0) {
        _addressBackView = [[AddressBackView alloc] initWithFrame:self.view.bounds];
       [_addressBackView.backBtn addTarget:self action:@selector(handleBackAddress) forControlEvents:(UIControlEventTouchUpInside)];
        _addressBackView.titleLB.text = @"友情提示";
        _addressBackView.conLB.text = @"请添加一个收获地址";
       
        [[UIApplication sharedApplication].keyWindow addSubview:_addressBackView];
        return;
        }
        [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)handleBackAddress {
    [_addressBackView removeFromSuperview];
}
#pragma mark tableView的代理事件
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _addressArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 40)];
    UIView *bgV2 =[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 39)];
    bgV2.backgroundColor = [UIColor whiteColor];
    [bgV addSubview:bgV2];
    
    bgV.backgroundColor = [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:0.8];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 200, 20)];
    label.text = @"我的地址";
    label.textColor = [UIColor grayColor];
    [bgV2 addSubview:label];
    
    return bgV;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyAddressCell"];
    cell.selectionStyle = kSeNone;
    AddressListModel *model = self.addressArray[indexPath.row];
    cell.nameLB.text = model.full_name;
    cell.phoneLB.text = model.tel;
    cell.addreLB.text = model.address;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     AddressListModel *model = self.addressArray[indexPath.row];
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *Dic = @{@"userid":saveDic[@"userid"], @"id":model.Id,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest postWithURLString:POST(EditDefaultAddress) parameters:Dic success:^(id responseObject) {
        
        if ([responseObject[@"ret"] intValue] != 200) {
            [[DSLHUD shareDSLHUD] showTextNoActivity:@"请求错误" timeLength:1.5];
            return ;
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark 添加地址按钮的点击事件
- (IBAction)addAddressBtnAction:(UIButton *)sender {
    AddAddressInfoController *addressAdd = [[AddAddressInfoController alloc] init];
    addressAdd.pushType = @"0";
    [self.navigationController pushViewController:addressAdd animated:YES];
    
    
}

@end
